package felix.things.router;

import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.core.env.Environment;
import org.springframework.util.StringUtils;

import java.util.Arrays;

/**
 * @author Felix
 * @date 2019/7/27
 */
@Slf4j
@SpringBootApplication
public class MqttRouterApplication {
    private static final String SPRING_CONFIG_NAME_KEY = "--spring.config.name";
    private static final String DEFAULT_SPRING_CONFIG_PARAM = SPRING_CONFIG_NAME_KEY + "=" + "mqtt-router";

    public static void main(String[] args) {
        try {
            SpringApplication app = new SpringApplication(MqttRouterApplication.class);
            Environment env = app.run(updateArguments(args)).getEnvironment();
            log(env);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            System.exit(1);
        }
    }

    private static String[] updateArguments(String[] args) {
        if (Arrays.stream(args).noneMatch(arg -> arg.startsWith(SPRING_CONFIG_NAME_KEY))) {
            String[] modifiedArgs = new String[args.length + 1];
            System.arraycopy(args, 0, modifiedArgs, 0, args.length);
            modifiedArgs[args.length] = DEFAULT_SPRING_CONFIG_PARAM;
            return modifiedArgs;
        }
        return args;
    }

    /**
     * 格式化运行成功后输出项目地址
     *
     * @param env
     */
    private static void log(Environment env) {
        String name = env.getProperty("spring.application.name");
        String port = env.getProperty("mqttrouter.config.port");
        String path = env.getProperty("mqttrouter.config.host");
        String ssl = env.getProperty("mqttrouter.config.ssl");
        String http = "true".equals(ssl) ? "ssl" : "tcp";
        name = StringUtils.isEmpty(name) ? "" : name;
        port = StringUtils.isEmpty(port) ? "1883" : port;
        path = StringUtils.isEmpty(path) ? "" : path;
        log.info(
                "\n----------------------------------------------------------\n"
                        + "\tApplication '{}' is running!\n"
                        + "\tConnect: \t{}://{}:{}\n"
                        + "----------------------------------------------------------",
                name, http, path, port);
    }

}
